package com.my.swas.sso.common.shiro;

import com.my.swas.common.jwt.JWTToken;
import com.my.swas.common.utils.CookieUtils;
import com.my.swas.common.constans.CommConst;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.mgt.RealmSecurityManager;
import org.apache.shiro.subject.SimplePrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.util.WebUtils;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;

/**
 * @Description:
 * @author: :MaYong
 */
public class ShiroUtils {


    public static void refresh() {
        RealmSecurityManager rsm = (RealmSecurityManager) SecurityUtils.getSecurityManager();
        MyRealm shiroRealm = (MyRealm) rsm.getRealms().iterator().next();
/*        Long userId = JWTUtils.getUserId();
        shiroRealm.clearUserAuthByUserId(Lists.newArrayList(userId));
        */
        shiroRealm.clearCachedAuthorizationInfo(SecurityUtils.getSubject().getPrincipals());
    }


    /**
     * 重新赋值权限(在比如:给一个角色临时添加一个权限,需要调用此方法刷新权限,否则还是没有刚赋值的权限)
     */
    public static void reloadAuthorizing() {
        RealmSecurityManager rsm = (RealmSecurityManager) SecurityUtils.getSecurityManager();
        MyRealm shiroRealm = (MyRealm) rsm.getRealms().iterator().next();
        Subject subject = SecurityUtils.getSubject();
        String realmName = subject.getPrincipals().getRealmNames().iterator().next();
        System.out.println("login.user=" + SecurityUtils.getSubject().getPrincipals().getPrimaryPrincipal().toString());
        System.out.println("login.token=" + SecurityUtils.getSubject().getPrincipal().toString());

        String jwtToken = subject.getPrincipals().getPrimaryPrincipal().toString();
        //第一个参数为用户名,第二个参数为realmName,test想要操作权限的用户
        SimplePrincipalCollection principals = new SimplePrincipalCollection(jwtToken, realmName);
        shiroRealm.getAuthorizationCache().remove(subject.getPrincipals());
        shiroRealm.getAuthorizationCache().remove(subject.getPrincipal());
        subject.releaseRunAs();
    }

    public static String getToken(ServletRequest request) {
        HttpServletRequest httpServletRequest = WebUtils.toHttp(request);
        String authorization = httpServletRequest.getHeader(JWTToken.AUTH_TOKEN);
        Boolean isSSO = StringUtils.isEmpty(authorization) && WebUtils.getRequestUri(httpServletRequest).contains(CommConst.ADMIN);
        Boolean isLogout = StringUtils.isEmpty(authorization) && WebUtils.getRequestUri(httpServletRequest).contains("logout");
        if (isSSO || isLogout) {//如何是sso系统访问，验证Cookie
            authorization = CookieUtils.getCookieValue(httpServletRequest, JWTToken.AUTH_TOKEN);
        }
        return authorization;
    }
}
